package model

import (
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"time"
)

type (
	ReDataModel struct {
		db *gorm.DB
	}
	ReData struct {
		ID int64 `gorm:"primary_key;AUTO_INCREMENT"`
		//		Unit     string         `gorm:"unit, varchar(10)"`    //@单位ppb,ppm,ug/m3,mg/m3
		ProPath  string    `gorm:"type:varchar(10)"` //@存储 5minute,hour,real
		Type     string    `gorm:"type:varchar(20)"` //airData, dev
		PickTime time.Time `gorm:"pick_time"`
		//上报项目的类型5minute hour
		PlatformId string `gorm:"type:varchar(40)"`
		//创建的平台的id
		Value datatypes.JSON `gorm:"air"`
	}
	AirReData struct {
		Pro   string
		Value float64
		Unit  string
		Flag  string
		//Co   float64 `gorm:"co"`
		//No   float64 `gorm:"no"`
		//No2  float64 `gorm:"no2"`
		//Nox  float64 `gorm:"nox"`
		//So2  float64 `gorm:"so2"`
		//O3   float64 `gorm:"o3"`
		//PM25 float64 `gorm:"pm25"`
		//PM10 float64 `gorm:"pm10"`
	}
)

func NewReDataModel(db *gorm.DB) *ReDataModel {
	return &ReDataModel{
		db: db,
	}
}

func (m *ReDataModel) Add(data ReData) error {
	return m.db.Create(&data).Error
}

func (m *ReDataModel) BatchData(datas []ReData) error {
	return m.db.Model(&ReData{}).CreateInBatches(&datas, len(datas)).Error
}

func (m *ReDataModel) DelData(datas []ReData) error {
	return m.db.Delete(&datas).Error
}

func (m *ReDataModel) Del(data ReData) error {
	return m.db.Model(&ReData{}).Delete(data.ID).Error
}

func (m *ReDataModel) FindByModel(id int64) ([]ReData, error) {
	var datas []ReData
	err := m.db.Model(&ReData{}).Where("platform_id=?", id).Find(&datas).Error
	return datas, err
}

func (m *ReDataModel) FindByType(id int64, style string) ([]ReData, error) {
	var datas []ReData
	err := m.db.Model(&ReData{}).Where("id = ? and pro_path = ?", id, style).Find(&datas).Error
	return datas, err
}

func (m *ReDataModel) FindByTime(id int64, start, end time.Time) ([]ReData, error) {
	var datas []ReData
	err := m.db.Model(&ReData{}).Where("id = ? and pick_time > ? and pick_time < ?", id, start, end).Find(&datas).Error
	return datas, err
}
